﻿using System;
using System.Linq;
using System.Windows;
using MinoChat.Ui.Enums;

namespace MinoChat.Ui;

/// <summary>
/// UI 层主题管理器，负责应用实际的视觉主题（Light/Dark/HighContrast）
/// 不包含 Auto 逻辑，Auto 由主项目的 ThemeService 处理
/// </summary>
public static class ThemeManager
{
    private static ThemeMode _currentThemeMode = ThemeMode.Light;

    /// <summary>
    /// 主题变化事件
    /// </summary>
    public static event EventHandler<ThemeMode>? ThemeChanged;

    /// <summary>
    /// 应用指定的主题
    /// </summary>
    /// <param name="themeMode">要应用的主题（仅支持 Light/Dark/HighContrast）</param>
    public static void Apply(ThemeMode themeMode)
    {
        if (Application.Current == null)
        {
            throw new InvalidOperationException("Application.Current is null. ThemeManager.Apply() must be called after Application is initialized.");
        }

        _currentThemeMode = themeMode;
        ApplyThemeInternal(themeMode);
    }

    /// <summary>
    /// 内部方法：应用实际的主题
    /// </summary>
    private static void ApplyThemeInternal(ThemeMode themeMode)
    {
        if (Application.Current == null)
            return;

        var mergedDictionaries = Application.Current.Resources.MergedDictionaries;

        // 查找并移除现有的 ThemesDictionary
        var existingThemeDictionary = mergedDictionaries
            .OfType<ThemesDictionary>()
            .FirstOrDefault();

        if (existingThemeDictionary != null)
        {
            mergedDictionaries.Remove(existingThemeDictionary);
        }

        // 创建并添加新的 ThemesDictionary
        var newThemeDictionary = new ThemesDictionary { ThemeMode = themeMode };
        // 将新主题字典插入到第一个位置，确保主题颜色优先级最高
        mergedDictionaries.Insert(0, newThemeDictionary);

        // 触发主题变化事件
        ThemeChanged?.Invoke(null, themeMode);
    }

    /// <summary>
    /// 获取当前应用的主题
    /// </summary>
    public static ThemeMode GetCurrentTheme()
    {
        return _currentThemeMode;
    }
}
